import { useEffect } from "react";
import { Form, Input, Select } from "antd";
import { useForm } from "antd/es/form/Form";
import { useComponentsStore } from "../../stores/components";
import { useComponentConfigStore, ComponentSetter, ComponentConfig } from "../../stores/component-config";

export const ComponentAttr = () => {
    const [form] = useForm();

    const { curComponentId, curComponent, updateComponentProps } = useComponentsStore();
    const { componentConfig } = useComponentConfigStore();

    useEffect(()=>{
        const data = form.getFieldsValue();
        form.setFieldsValue({...data, ...curComponent?.props});
    }, [curComponent])

    if(!curComponent || !curComponentId) return null;

    const renderFormElement = ({ type, options }: ComponentSetter):React.ReactElement | null => {
        if(type === 'select') {
            return <Select options={options}></Select>
        }else if(type === 'input') {
            return <Input />
        }
        return null
    }
    const valueChange = (changeValues: ComponentConfig) => {
        if(curComponentId) {
            updateComponentProps(curComponentId, changeValues)
        }
    }


    return (
        <Form 
            form={form}
            labelCol={{span: 8}}
            wrapperCol={{span: 14}}
            onValuesChange={valueChange}
        >
            <Form.Item label="组件Id">
                <Input value={curComponent?.id} disabled />
            </Form.Item>
            <Form.Item label="组件名称">
                <Input value={curComponent?.name} disabled />
            </Form.Item>
            <Form.Item label="组件描述">
                <Input value={curComponent?.desc} disabled />
            </Form.Item>
            {
                componentConfig[curComponent!.name]?.setter?.map(setter => (
                    <Form.Item key={setter.name} name={setter.name} label={setter.label} >
                        { renderFormElement(setter) }
                    </Form.Item>
                ))
            }
        </Form>
    )
}